package yb.ecp.fast.user.service;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.util.StringUtil;
import yb.ecp.fast.user.manager.AuthInfoManager;
import yb.ecp.fast.user.service.VO.AuthInfoVO;

import java.awt.image.BufferedImage;

/**
 * Created by john on 2017/11/17.
 */
@Service
@RefreshScope
public class AuthService {
    @Autowired
    DefaultKaptcha defaultKaptcha;
    @Autowired
    FastGenClient genClient;
    @Autowired
    AuthInfoManager authInfoManager;

    @Value("${login.verifyCode.default.flag:close}")
    private String verifyCodeFlag;

    public AuthInfoVO createAuthInfo()
    {
        AuthInfoVO authInfoVO = new AuthInfoVO();
        authInfoVO.setAuthId(genClient.newGuidText().getValue());
        if ("open".equals(verifyCodeFlag.trim()))
        {
            authInfoVO.setVerifyCode("1234");
        }
        else
        {
            authInfoVO.setVerifyCode(defaultKaptcha.createText());
        }
        authInfoManager.savAuthKaptcha(authInfoVO.getAuthId(), authInfoVO.getVerifyCode());
        if (!"open".equals(verifyCodeFlag.trim())) {
            authInfoVO.setVerifyCode(null);
        }
        return authInfoVO;
    }
    public BufferedImage createVerifyImg(String authId){
        String text = authInfoManager.getRedisCode(authId);
        if (StringUtil.isNullOrSpace(text)){
            text=defaultKaptcha.createText();
            authInfoManager.savAuthKaptcha(authId,text);
        }
        return defaultKaptcha.createImage(text);
    }

}
